<template>
  <view>
    <van-notice-bar left-icon="volume-o" scrollable text="可设置3个号码，当第一个号码未接通时，将会继续拨打第二个号码，依次类推" />
    <view class="c-pd">
      <van-cell-group inset>
        <van-field :value="state.onePhone" placeholder="请输入联系电话" :border="false" clearable label="第一联系人" @change="state.onePhone = $event.detail" />
        <van-field :value="state.twoPhone" placeholder="请输入联系电话" :border="false" label="第二联系人" clearable @change="state.twoPhone = $event.detail" />
        <van-field :value="state.threePhone" placeholder="请输入联系电话" :border="false" label="第三联系人" clearable @change="state.threePhone = $event.detail" />
      </van-cell-group>
    </view>
    <view class="w-full fixed c-pd" :style="{ bottom: `${store.$state.systemInfo.safeAreaInsets!.bottom}px` }">
      <van-button type="primary" block @click="submitInfo">保存</van-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import EquipRequest from '@/request/equipRequest';
import useToast from '@/hooks/useToast';
import useModal from '@/hooks/useModal';
import { useAppStore } from '@/store';

interface IState {
  equipId: number;
  onePhone: string;
  twoPhone: string;
  threePhone: string;
}

const store = useAppStore();

const { showToast } = useToast();

const { showModal } = useModal();

const state = reactive<IState>({
  equipId: 0,
  onePhone: '',
  twoPhone: '',
  threePhone: '',
});

onLoad((options) => {
  if (!options) return;
  state.equipId = options.equipId;
  getContact();
});

const submitInfo = () => {
  const phoneReg = /^\d+$/;
  if (!state.onePhone && !state.twoPhone && !state.threePhone) {
    showModal('至少填写一个联系方式');
    return false;
  }
  if (state.onePhone && !phoneReg.test(state.onePhone)) {
    showModal('第一号码格式错误');
    return false;
  }
  if (state.twoPhone && !phoneReg.test(state.twoPhone)) {
    showModal('第二号码格式错误');
    return false;
  }
  if (state.threePhone && !phoneReg.test(state.threePhone)) {
    showModal('第三号码格式错误');
    return false;
  }
  EquipRequest.SetContact({
    equipId: state.equipId,
    fastPhones: state.onePhone + ',' + state.twoPhone + ',' + state.threePhone,
    hasLoading: true,
  }).then((res) => {
    if (res.status === 0) {
      showToast('操作成功', 'success');
      setTimeout(() => {
        getContact();
      }, 1000);
    }
  });
};

const getContact = () => {
  EquipRequest.GetContact({
    equipId: state.equipId,
    hasLoading: true,
  }).then((res) => {
    let fastPhonesArr = res.data.fastPhones.includes(',')
      ? res.data.fastPhones
          .split(',')
          .map((item) => item.trim())
          .filter((item) => item !== '')
      : [res.data.fastPhones.trim()];

    state.onePhone = fastPhonesArr[0];
    state.twoPhone = fastPhonesArr[1];
    state.threePhone = fastPhonesArr[2];
  });
};
</script>
